<!-- src/components/Cards/BaseCard.vue -->
<template>
  <div 
    class="base-card" 
    :style="cardStyle"
    v-if="visible"
  >
    <!-- 顶部拖拽区域 -->
    <div 
      class="base-card-header"
      @mousedown.stop="startDrag"
    >
      <span class="base-card-title">任务卡片</span>
      <button class="base-card-close" @click="handleClose">×</button>
    </div>
    
    <!-- 内容区域 -->
    <div class="base-card-content">
      <!-- 标题输入框 -->
      <div class="title-input-section">
        <input
          ref="titleInputRef"
          v-model="title"
          type="text"
          placeholder="输入标题"
          class="title-input"
          @focus="handleTitleFocus"
          @blur="handleTitleBlur"
        >
      </div>

      <!-- 活动/任务切换按钮 -->
      <div class="tab-buttons">
        <button 
          class="tab-button"
          :class="{ active: activeTab === 'activity' }"
          @click="activeTab = 'activity'"
        >
          活动
        </button>
        <button 
          class="tab-button"
          :class="{ active: activeTab === 'task' }"
          @click="activeTab = 'task'"
        >
          任务
        </button>
      </div>

      <!-- 活动内容 -->
      <div v-if="activeTab === 'activity'" class="activity-content">
        <!-- 日期范围栏 -->
        <div class="activity-row time-range-row" ref="timeRangeRowRef">
          <span class="icon">📅</span>
          <div class="time-range-display">
            <!-- 显示状态内容 -->
            <div v-if="!isEditingDateRange" class="display-content">
              <div class="date-range-text">{{ formatDateRangeDisplay() }}</div>
              <button class="edit-date-button" @click.stop="enterEditMode" title="修改日期">
                <span class="edit-icon">🔧</span>
              </button>
            </div>
            
            <!-- 编辑状态内容 -->
            <div v-else class="edit-content">
              <!-- 第一行：起始日期和终止日期 -->
              <div class="date-inputs-row">
                <div class="date-input-group">
                  <label class="date-label">起始日期</label>
                  <div class="date-value fixed-date">
                    {{ formatActivityDate(activityStartDate) }}
                  </div>
                </div>
                <div class="date-input-group">
                  <label class="date-label">终止日期</label>
                  <div 
                    class="date-value editable-date" 
                    @click="isAllDay && showEndDatePicker()"
                    :class="{ 'all-day-mode': isAllDay, 'time-mode': !isAllDay }"
                  >
                    <span v-if="isAllDay">{{ formatActivityDate(activityEndDate) }}</span>
                    <span v-else>{{ activityStartTime }} ~ {{ activityEndTime }}</span>
                  </div>
                  <!-- 终止时间 DatePicker -->
                  <div class="date-picker-container" v-if="showEndDatePickerFlag">
                    <DatePicker
                      :visible="showEndDatePickerFlag"
                      :initial-date="activityEndDate"
                      @select="handleEndDateSelect"
                      @close="hideEndDatePicker"
                    />
                  </div>
                </div>
              </div>
              
              <!-- 第二行：全天复选框 -->
              <div class="all-day-row">
                <div class="all-day-checkbox">
                  <input 
                    type="checkbox" 
                    id="all-day" 
                    v-model="isAllDay"
                    @change="handleAllDayChange"
                  >
                  <label for="all-day">全天</label>
                </div>
              </div>

              <!-- 第三行：时间选择区域（非全天时显示） -->
              <div v-if="!isAllDay" class="time-inputs-row">
                <div class="time-input-group">
                  <label>开始时刻</label>
                  <div class="time-input-wrapper">
                    <input
                      v-model="activityStartTime"
                      type="text"
                      placeholder="HH:mm"
                      class="time-input"
                      @blur="validateStartTime"
                      @focus="showStartTimeDropdown = true"
                      @click.stop
                    >
                    <select 
                      v-model="activityStartTime" 
                      class="time-dropdown"
                      v-if="showStartTimeDropdown"
                      @blur="showStartTimeDropdown = false"
                      @change="handleStartTimeChange"
                      @click.stop
                    >
                      <option 
                        v-for="time in timeOptions" 
                        :key="'start-' + time"
                        :value="time"
                      >
                        {{ time }}
                      </option>
                    </select>
                  </div>
                </div>
                <div class="time-input-group">
                  <label>结束时刻</label>
                  <div class="time-input-wrapper">
                    <input
                      v-model="activityEndTime"
                      type="text"
                      placeholder="HH:mm"
                      class="time-input"
                      @blur="validateEndTime"
                      @focus="showEndTimeDropdown = true"
                      @click.stop
                    >
                    <select 
                      v-model="activityEndTime" 
                      class="time-dropdown"
                      v-if="showEndTimeDropdown"
                      @blur="showEndTimeDropdown = false"
                      @change="handleEndTimeChange"
                      @click.stop
                    >
                      <option 
                        v-for="time in timeOptions" 
                        :key="'end-' + time"
                        :value="time"
                      >
                        {{ time }}
                      </option>
                    </select>
                  </div>
                </div>
              </div>

              <!-- 操作按钮 -->
              <div class="date-range-actions">
                <button class="confirm-btn" @click="confirmDateRange">确定</button>
                <button class="cancel-btn" @click="cancelDateRange">取消</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 地点设置 -->
        <div class="activity-row">
          <span class="icon">📍</span>
          <input
            v-model="activityLocation"
            type="text"
            placeholder="添加地点"
            class="location-input"
          >
        </div>
        
        <!-- 备注 -->
        <div class="activity-row">
          <span class="icon">📝</span>
          <input
            v-model="activityNote"
            type="text"
            placeholder="添加备注"
            class="note-input"
          >
        </div>
      </div>

      <!-- 任务内容 -->
      <div v-else class="task-content">
        <!-- 时间 -->
        <div class="task-row time-row" ref="timeRowRef">
          <span class="icon">🕒</span>
          <div class="time-display" @click="showDatePicker">
            {{ formatTaskTime() }}
          </div>
          
          <!-- DatePicker 容器 -->
          <div class="date-picker-container" v-if="showDatePickerFlag">
            <DatePicker
              :visible="showDatePickerFlag"
              :initial-date="cardDate"
              @select="handleDateSelect"
              @close="hideDatePicker"
            />
          </div>
        </div>
        
        <!-- 截止时间 -->
        <div class="task-row">
          <span class="icon">🎯</span>
          <div class="deadline-section">
            <!-- 显示状态：无截止日期 -->
            <div v-if="!isEditingDeadline && !taskDeadline" class="deadline-display" @click="startEditDeadline">
              添加截止时间
            </div>
            
            <!-- 显示状态：有截止日期 -->
            <div v-if="!isEditingDeadline && taskDeadline" class="deadline-display" @click="startEditDeadline">
              {{ formatDeadlineDate(taskDeadline) }}
            </div>
            
            <!-- 编辑状态 -->
            <div v-if="isEditingDeadline" class="deadline-edit">
              <div class="deadline-date" @click="showDeadlineDatePicker">
                {{ formatDeadlineDate(editingDeadlineDate) }}
              </div>
              <button class="deadline-cancel-btn" @click="cancelDeadlineEdit">取消</button>
              
              <!-- 截止时间 DatePicker 容器 -->
              <div class="date-picker-container" v-if="showDeadlineDatePickerFlag">
                <DatePicker
                  :visible="showDeadlineDatePickerFlag"
                  :initial-date="editingDeadlineDate"
                  @select="handleDeadlineDateSelect"
                  @close="hideDeadlineDatePicker"
                />
              </div>
            </div>
          </div>
        </div>
        
        <!-- 备注 -->
        <div class="task-row">
          <span class="icon">📝</span>
          <input
            v-model="taskNote"
            type="text"
            placeholder="添加备注"
            class="note-input"
          >
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="base-card-footer">
      <button class="save-button" @click="handleSave">
        保存
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import DatePicker from '@/components/Calendar/DatePicker.vue'
import type { baseCard, activityCard, missionCard } from '@/types/card'
import { useCardStore } from '@/store/card'
import { ElMessage } from 'element-plus'

const cardStore = useCardStore()

interface Props {
  position: {
    x: number
    y: number
  }
  selectedDate?: Date // 接收选中的日期
  initialAllDay?: boolean
  initialStartTime?: string // HH:mm
  initialEndTime?: string   // HH:mm
  editCardData?: activityCard | missionCard | null // 编辑模式时传入的卡片数据
  creationContext?: 'grid' | 'allDay'
}

interface Emits {
  (e: 'close'): void
  (e: 'drag', position: { x: number; y: number }): void
  (e: 'save', cardData: activityCard | missionCard): void // 保存事件
  (e: 'time-change', data: { allDay: boolean; startTime: string; endTime: string; startDate: Date; endDate: Date }): void // 时间变化事件
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(true)
const position = reactive({
  x: props.position.x,
  y: props.position.y
})
const isDragging = ref(false)
const dragOffset = reactive({ x: 0, y: 0 })

// 新增状态
const title = ref('')
const activeTab = ref<'activity' | 'task'>('activity')
const titleInputRef = ref<HTMLInputElement | null>(null)
const timeRowRef = ref<HTMLDivElement | null>(null)
const timeRangeRowRef = ref<HTMLDivElement | null>(null)

// DatePicker 相关状态
const showDatePickerFlag = ref(false)
const cardDate = ref(props.selectedDate || new Date())

// 活动相关状态
const activityStartDate = ref(props.selectedDate || new Date())
const activityEndDate = ref(new Date(activityStartDate.value))
activityEndDate.value.setDate(activityEndDate.value.getDate() + 1) // 默认终止日期为起始日期+1天
const showEndDatePickerFlag = ref(false)
const activityLocation = ref('')
const activityNote = ref('')

// 日期范围编辑状态
const isEditingDateRange = ref(false)
const isAllDay = ref(props.initialAllDay ?? true)
// 保存初始时间值，用于取消时恢复
const initialStartTime = ref(props.initialStartTime || '00:00')
const initialEndTime = ref(props.initialEndTime || '23:45')
// 保存编辑前的值，用于取消时恢复（在进入编辑模式时保存）
const beforeEditStartTime = ref('')
const beforeEditEndTime = ref('')
const activityStartTime = ref(initialStartTime.value)
const activityEndTime = ref(initialEndTime.value)
const showStartTimeDropdown = ref(false)
const showEndTimeDropdown = ref(false)

// 任务相关状态
const taskNote = ref('')
const taskDeadline = ref<Date | undefined>(undefined)

// 截止时间编辑状态
const isEditingDeadline = ref(false)
const showDeadlineDatePickerFlag = ref(false)
const editingDeadlineDate = ref<Date>(new Date())

const taskCreationContext = ref<'grid' | 'allDay'>(props.creationContext ?? 'grid')

// 编辑模式：如果传入了editCardData，初始化所有字段
// 使用 watch 监听 editCardData 变化，支持动态更新
const initEditData = () => {
  if (props.editCardData) {
    const card = props.editCardData
    title.value = card.title || ''
    activeTab.value = card.type
    
    if (card.type === 'activity') {
      const activity = card as activityCard
      activityStartDate.value = new Date(activity.startDate)
      activityEndDate.value = new Date(activity.endDate)
      activityLocation.value = activity.location || ''
      activityNote.value = activity.remark || ''
      isAllDay.value = activity.allDayLong
      
      if (!activity.allDayLong && activity.beginTime && activity.endTime) {
        const startDate = new Date(activity.beginTime)
        const endDate = new Date(activity.endTime)
        const startTimeStr = `${startDate.getHours().toString().padStart(2,'0')}:${startDate.getMinutes().toString().padStart(2,'0')}`
        const endTimeStr = `${endDate.getHours().toString().padStart(2,'0')}:${endDate.getMinutes().toString().padStart(2,'0')}`
        // 保存初始时间值
        initialStartTime.value = startTimeStr
        initialEndTime.value = endTimeStr
        activityStartTime.value = initialStartTime.value
        activityEndTime.value = initialEndTime.value
      } else {
        // 全天模式，使用默认时间
        initialStartTime.value = '00:00'
        initialEndTime.value = '23:45'
        activityStartTime.value = initialStartTime.value
        activityEndTime.value = initialEndTime.value
      }
    } else if (card.type === 'task') {
      const mission = card as missionCard
      cardDate.value = new Date(mission.date)
      taskNote.value = mission.remark || ''
      taskDeadline.value = mission.deadline ? new Date(mission.deadline) : undefined
      taskCreationContext.value = mission.originContext ?? 'grid'
    }
  } else {
    // 新建模式，重置为默认值
    title.value = ''
    activeTab.value = 'activity'
    activityStartDate.value = props.selectedDate || new Date()
    activityEndDate.value = new Date(activityStartDate.value)
    activityEndDate.value.setDate(activityEndDate.value.getDate() + 1)
    activityLocation.value = ''
    activityNote.value = ''
    isAllDay.value = props.initialAllDay ?? true
    // 更新初始时间值
    initialStartTime.value = props.initialStartTime || '00:00'
    initialEndTime.value = props.initialEndTime || '23:45'
    activityStartTime.value = initialStartTime.value
    activityEndTime.value = initialEndTime.value
    // 初始化编辑前的值
    beforeEditStartTime.value = initialStartTime.value
    beforeEditEndTime.value = initialEndTime.value
    cardDate.value = props.selectedDate || new Date()
    taskNote.value = ''
    taskDeadline.value = undefined
    taskCreationContext.value = props.creationContext ?? 'grid'
  }
}

// 初始化
initEditData()

// 监听 editCardData 变化
watch(() => props.editCardData, (newValue, oldValue) => {
  // 当 editCardData 从有值变为 null 时，确保重置为新建模式
  if (!newValue && oldValue) {
    // 强制重置为新建模式
    initEditData()
  } else {
    initEditData()
  }
}, { deep: true, immediate: false })

// 监听 initialStartTime 和 initialEndTime 的变化，更新初始值
watch(() => [props.initialStartTime, props.initialEndTime], ([newStartTime, newEndTime]) => {
  if (newStartTime !== undefined) {
    initialStartTime.value = newStartTime
    // 如果当前不在编辑模式，同时更新当前时间值和编辑前的值
    if (!isEditingDateRange.value) {
      activityStartTime.value = newStartTime
      beforeEditStartTime.value = newStartTime
    }
  }
  if (newEndTime !== undefined) {
    initialEndTime.value = newEndTime
    // 如果当前不在编辑模式，同时更新当前时间值和编辑前的值
    if (!isEditingDateRange.value) {
      activityEndTime.value = newEndTime
      beforeEditEndTime.value = newEndTime
    }
  }
}, { immediate: false })

// 监听标题变化，更新临时卡片标题
watch(() => title.value, (newTitle) => {
  // 只有在显示 BaseCard 且存在临时按钮时才更新
  if (cardStore.showBaseCard && cardStore.tempButtonDate) {
    cardStore.updateTempCardTitle(newTitle)
  }
})

// 卡片尺寸
const cardWidth = 360
const cardHeight = 420
const margin = 10

// 生成时间选项（15分钟间隔，00:00 到 23:45）
const timeOptions = computed(() => {
  const options = []
  for (let hour = 0; hour < 24; hour++) {
    for (let minute = 0; minute < 60; minute += 15) {
      const timeString = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
      options.push(timeString)
    }
  }
  return options
})

// 计算卡片样式（包含边界检查）
const cardStyle = computed(() => {
  let adjustedX = position.x
  let adjustedY = position.y
  
  // 水平方向边界检查
  if (adjustedX + cardWidth > window.innerWidth) {
    adjustedX = window.innerWidth - cardWidth - margin
  }
  if (adjustedX < margin) {
    adjustedX = margin
  }
  
  // 垂直方向边界检查
  if (adjustedY + cardHeight > window.innerHeight) {
    adjustedY = window.innerHeight - cardHeight - margin
  }
  if (adjustedY < margin) {
    adjustedY = margin
  }
  
  return {
    left: `${adjustedX}px`,
    top: `${adjustedY}px`,
    transform: isDragging.value ? 'scale(1.02)' : 'scale(1)'
  }
})

// 开始拖拽
const startDrag = (event: MouseEvent) => {
  isDragging.value = true
  dragOffset.x = event.clientX - position.x
  dragOffset.y = event.clientY - position.y
  
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
}

// 处理拖拽
const handleDrag = (event: MouseEvent) => {
  if (!isDragging.value) return
  
  // 计算新位置
  let newX = event.clientX - dragOffset.x
  let newY = event.clientY - dragOffset.y
  
  // 边界检查
  if (newX < margin) newX = margin
  if (newX > window.innerWidth - cardWidth - margin) newX = window.innerWidth - cardWidth - margin
  if (newY < margin) newY = margin
  if (newY > window.innerHeight - cardHeight - margin) newY = window.innerHeight - cardHeight - margin
  
  position.x = newX
  position.y = newY
  
  emit('drag', { x: position.x, y: position.y })
}

// 停止拖拽
const stopDrag = () => {
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
}

// 关闭卡片
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 生成id
const generateId = (): string => {
  return Date.now().toString() + Math.random().toString(36).substr(2, 9)
}

// 保存卡片数据
const handleSave = () => {
  // 如果当前在编辑模式下，先退出编辑模式（使用当前值，不恢复）
  // 这样可以确保保存时使用的是最终显示的值
  if (isEditingDateRange.value) {
    isEditingDateRange.value = false
    // 更新编辑前的值，为下次编辑做准备
    beforeEditStartTime.value = activityStartTime.value
    beforeEditEndTime.value = activityEndTime.value
  }
  
  if (activeTab.value === 'activity') {
    let cardData: activityCard = {
      id: props.editCardData?.id || generateId(), // 编辑模式使用原ID，新建模式生成新ID
      createdAt: props.editCardData?.createdAt || new Date(),
      updatedAt: new Date(),
      type: activeTab.value,
      date: props.selectedDate || new Date(),
      title: title.value,
      startDate: activityStartDate.value,
      endDate: activityEndDate.value,
      location: activityLocation.value,
      remark: activityNote.value,
      allDayLong: isAllDay.value,
    }

    // 如果不是全天，添加开始时间和结束时间
    if (!isAllDay.value) {
      // 验证时间格式
      if (!validateTimeFormat(activityStartTime.value) || !validateTimeFormat(activityEndTime.value)) {
        ElMessage.warning('时间格式不正确，请使用 HH:mm 格式')
        return
      }

      // 验证结束时间不早于开始时间
      if (!validateTimeOrder(activityStartTime.value, activityEndTime.value)) {
        ElMessage.warning('结束时间不能早于开始时间')
        return
      }

      // 设置开始时间和结束时间
      cardData.beginTime = combineDateAndTime(activityStartDate.value, activityStartTime.value)
      cardData.endTime = combineDateAndTime(activityEndDate.value, activityEndTime.value)
    }

    // 触发保存事件
    emit('save', cardData)
    // 关闭卡片并传递保存的数据
    visible.value = false
    emit('close')
  } else {
    // 统一处理空标题：如果标题为空，使用"新任务"
    const normalizedTitle = title.value && title.value.trim() ? title.value.trim() : '新任务'
    
    let cardData: missionCard = {
      id: props.editCardData?.id || generateId(), // 编辑模式使用原ID，新建模式生成新ID
      createdAt: props.editCardData?.createdAt || new Date(),
      updatedAt: new Date(),
      type: activeTab.value,
      date: cardDate.value,
      title: normalizedTitle, // 使用规范化后的标题
      missionDate: cardDate.value,
      deadline: taskDeadline.value,
      remark: taskNote.value,
      originContext: taskCreationContext.value
    }

    if (taskCreationContext.value === 'grid') {
      const timeSource = initialStartTime.value || props.initialStartTime || '00:00'
      cardData.beginTime = combineDateAndTime(cardDate.value, timeSource)
    } else if (props.editCardData?.type === 'task' && props.editCardData.beginTime) {
      cardData.beginTime = props.editCardData.beginTime
    } else {
      cardData.beginTime = undefined
    }

    // 触发保存事件
    emit('save', cardData)
    // 关闭卡片并传递保存的数据
    visible.value = false
    emit('close')
  }
}

// 组合日期和时间
const combineDateAndTime = (date: Date, timeStr: string): Date => {
  const [hours, minutes] = timeStr.split(':').map(Number)
  const newDate = new Date(date)
  newDate.setHours(hours, minutes, 0, 0)
  return newDate
}

// 验证时间格式 (HH:mm)
const validateTimeFormat = (timeStr: string): boolean => {
  const timeRegex = /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/
  return timeRegex.test(timeStr)
}

// 验证时间顺序
const validateTimeOrder = (startTime: string, endTime: string): boolean => {
  const [startHours, startMinutes] = startTime.split(':').map(Number)
  const [endHours, endMinutes] = endTime.split(':').map(Number)
  
  if (endHours < startHours) return false
  if (endHours === startHours && endMinutes <= startMinutes) return false
  return true
}

// 验证开始时间
const validateStartTime = () => {
  if (!validateTimeFormat(activityStartTime.value)) {
    ElMessage.warning('时间格式不正确，请使用 HH:mm 格式（如 00:00）')
    activityStartTime.value = '00:00'
  }
}

// 验证结束时间
const validateEndTime = () => {
  if (!validateTimeFormat(activityEndTime.value)) {
    ElMessage.warning('时间格式不正确，请使用 HH:mm 格式（如 23:45）')
    activityEndTime.value = '23:45'
    return
  }
  
  if (!validateTimeOrder(activityStartTime.value, activityEndTime.value)) {
    ElMessage.warning('结束时间不能早于开始时间')
    activityEndTime.value = '23:45'
  }
}

// 标题输入框聚焦处理
const handleTitleFocus = () => {
  // 可以添加聚焦时的样式变化
}

const handleTitleBlur = () => {
  // 可以添加失焦时的处理
}

// 进入编辑模式
const enterEditMode = () => {
  // 保存编辑前的值，用于取消时恢复
  beforeEditStartTime.value = activityStartTime.value
  beforeEditEndTime.value = activityEndTime.value

  // 确保在非全天模式下，终止日期与起始日期相同
  if (!isAllDay.value) {
    activityEndDate.value = new Date(activityStartDate.value)
  }
  
  nextTick(() => {
    isEditingDateRange.value = true
  })
}

// 通知父组件时间变化
const notifyTimeChange = () => {
  emit('time-change', {
    allDay: isAllDay.value,
    startTime: activityStartTime.value,
    endTime: activityEndTime.value,
    startDate: new Date(activityStartDate.value),
    endDate: new Date(activityEndDate.value)
  })
}

// 确认日期范围
const confirmDateRange = () => {
  // 验证逻辑
  if (isAllDay.value) {
    // 全天模式：终止日期至少为起始日期+1天
    if (activityEndDate.value <= activityStartDate.value) {
      ElMessage.warning('终止日期必须晚于起始日期')
      return
    }
  } else {
    // 非全天模式：起始日期和终止日期必须为同一天
    if (activityEndDate.value.toDateString() !== activityStartDate.value.toDateString()) {
      ElMessage.warning('非全天模式下，起始日期和终止日期必须为同一天')
      return
    }
    // 验证时间格式和顺序
    if (!validateTimeFormat(activityStartTime.value) || !validateTimeFormat(activityEndTime.value)) {
      ElMessage.warning('时间格式不正确，请使用 HH:mm 格式')
      return
    }
    if (!validateTimeOrder(activityStartTime.value, activityEndTime.value)) {
      ElMessage.warning('结束时间必须晚于开始时间')
      return
    }
  }
  
  isEditingDateRange.value = false
  // 更新编辑前的值，为下次编辑做准备
  beforeEditStartTime.value = activityStartTime.value
  beforeEditEndTime.value = activityEndTime.value
  // 通知父组件时间变化
  notifyTimeChange()
}

// 取消日期范围编辑
const cancelDateRange = () => {
  isEditingDateRange.value = false
  // 重置为编辑前的值（进入编辑模式时保存的值）
  // 注意：非全天模式下，结束日期应该与开始日期相同
  activityStartTime.value = beforeEditStartTime.value || initialStartTime.value
  activityEndTime.value = beforeEditEndTime.value || initialEndTime.value
  // 如果是非全天模式，确保结束日期与开始日期相同
  if (!isAllDay.value) {
    activityEndDate.value = new Date(activityStartDate.value)
  } else {
    // 全天模式：结束日期为开始日期+1天
    activityEndDate.value = new Date(activityStartDate.value)
    activityEndDate.value.setDate(activityEndDate.value.getDate() + 1)
  }
  // 通知父组件恢复到编辑前的值
  notifyTimeChange()
}

// 处理全天状态变化
const handleAllDayChange = () => {
  if (isAllDay.value) {
    // 切换到全天模式：重置时间为默认值，确保终止日期至少为起始日期+1天
    activityStartTime.value = '00:00'
    activityEndTime.value = '23:45'
    if (activityEndDate.value <= activityStartDate.value) {
      activityEndDate.value = new Date(activityStartDate.value)
      activityEndDate.value.setDate(activityEndDate.value.getDate() + 1)
    }
  } else {
    // 切换到非全天模式：确保起始日期和终止日期为同一天
    activityEndDate.value = new Date(activityStartDate.value)
  }
  // 通知父组件时间变化
  notifyTimeChange()
}

// 格式化日期范围显示
const formatDateRangeDisplay = () => {
  const startStr = formatActivityDate(activityStartDate.value)
  const endStr = formatActivityDate(activityEndDate.value)
  
  if (isAllDay.value) {
    return `${startStr} ~ ${endStr}`
  } else {
    return `${startStr} ${activityStartTime.value} - ${activityEndTime.value}`
  }
}

// 任务时间点击处理 - 显示DatePicker
const showDatePicker = () => {
  showDatePickerFlag.value = true
}

// 隐藏DatePicker
const hideDatePicker = () => {
  showDatePickerFlag.value = false
}

// 处理日期选择
const handleDateSelect = (date: Date) => {
  cardDate.value = date
}

// 显示终止时间DatePicker
const showEndDatePicker = () => {
  if (isEditingDateRange.value) {
    showEndDatePickerFlag.value = true
  }
}

// 隐藏终止时间DatePicker
const hideEndDatePicker = () => {
  showEndDatePickerFlag.value = false
}

// 处理终止日期选择
const handleEndDateSelect = (date: Date) => {
  if (isAllDay.value) {
    // 全天模式：不能比起始日期早
    if (date < activityStartDate.value) {
      ElMessage.warning('终止日期不能比起始日期早')
      return
    }
  } else {
    // 非全天模式：必须与起始日期同一天
    if (date.toDateString() !== activityStartDate.value.toDateString()) {
      ElMessage.warning('非全天模式下，终止日期必须与起始日期相同')
      return
    }
  }
  activityEndDate.value = new Date(date.getTime())
  // 只有在确认后才通知父组件时间变化，编辑模式下不实时通知
  // 这样可以避免取消时baseCardDefaults已经被修改的问题
  // notifyTimeChange()
}

// 处理开始时间变化
const handleStartTimeChange = () => {
  showStartTimeDropdown.value = false
  // 自动调整结束时间，确保结束时间晚于开始时间
  if (!validateTimeOrder(activityStartTime.value, activityEndTime.value)) {
    // 如果结束时间早于开始时间，自动设置为开始时间+1小时
    const [hours, minutes] = activityStartTime.value.split(':').map(Number)
    let newHours = hours + 1
    if (newHours >= 24) newHours = 23
    activityEndTime.value = `${newHours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  }
  // 只有在确认后才通知父组件时间变化，编辑模式下不实时通知
  // 这样可以避免取消时baseCardDefaults已经被修改的问题
  // notifyTimeChange()
}

// 处理结束时间变化
const handleEndTimeChange = () => {
  showEndTimeDropdown.value = false
  // 验证结束时间不早于开始时间
  if (!validateTimeOrder(activityStartTime.value, activityEndTime.value)) {
    ElMessage.warning('结束时间不能早于开始时间')
    activityEndTime.value = '23:45'
  }
  // 只有在确认后才通知父组件时间变化，编辑模式下不实时通知
  // 这样可以避免取消时baseCardDefaults已经被修改的问题
  // notifyTimeChange()
}

// 格式化活动日期
const formatActivityDate = (date: Date) => {
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const weekDay = weekDays[date.getDay()]
  return `${month}月${day}日 周${weekDay}`
}

// 格式化任务时间
const formatTaskTime = () => {
  const month = cardDate.value.getMonth() + 1
  const day = cardDate.value.getDate()
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const weekDay = weekDays[cardDate.value.getDay()]
  return `${month}月${day}日 周${weekDay}`
}

// 格式化截止日期
const formatDeadlineDate = (date: Date) => {
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  const weekDay = weekDays[date.getDay()]
  return `${month}月${day}日 周${weekDay}`
}

// 开始编辑截止时间
const startEditDeadline = () => {
  isEditingDeadline.value = true
  // 设置默认截止日期为起始日期的第二天，确保不早于起始日期
  const startDate = new Date(cardDate.value)
  const tomorrow = new Date(startDate)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  // 如果已有截止日期且不早于起始日期，则使用已有的，否则使用默认的明天
  if (taskDeadline.value) {
    const deadlineDate = new Date(taskDeadline.value)
    deadlineDate.setHours(0, 0, 0, 0)
    startDate.setHours(0, 0, 0, 0)
    
    if (deadlineDate >= startDate) {
      editingDeadlineDate.value = new Date(taskDeadline.value)
    } else {
      editingDeadlineDate.value = tomorrow
      taskDeadline.value = tomorrow
    }
  } else {
    editingDeadlineDate.value = tomorrow
  }
}

// 取消截止时间编辑
const cancelDeadlineEdit = () => {
  isEditingDeadline.value = false
  // 如果当前截止日期早于起始日期，也清除它
  if (taskDeadline.value) {
    const deadlineDate = new Date(taskDeadline.value)
    deadlineDate.setHours(0, 0, 0, 0)
    const startDate = new Date(cardDate.value)
    startDate.setHours(0, 0, 0, 0)
    
    if (deadlineDate < startDate) {
      taskDeadline.value = undefined
    }
  }
}

// 显示截止时间DatePicker
const showDeadlineDatePicker = () => {
  showDeadlineDatePickerFlag.value = true
}

// 隐藏截止时间DatePicker
const hideDeadlineDatePicker = () => {
  showDeadlineDatePickerFlag.value = false
}

// 处理截止日期选择
const handleDeadlineDateSelect = (date: Date) => {
  // 验证截止日期不能早于起始日期
  const selectedDate = new Date(date.getTime())
  selectedDate.setHours(0, 0, 0, 0) // 只比较日期部分
  
  const startDate = new Date(cardDate.value)
  startDate.setHours(0, 0, 0, 0) // 只比较日期部分
  
  if (selectedDate < startDate) {
    ElMessage.warning('截止日期不能早于起始日期')
    // 强制设置为起始日期的后一天
    const nextDay = new Date(startDate)
    nextDay.setDate(nextDay.getDate() + 1)
    editingDeadlineDate.value = nextDay
    taskDeadline.value = nextDay
  } else {
    editingDeadlineDate.value = new Date(date.getTime())
    taskDeadline.value = new Date(date.getTime())
  }
  
  isEditingDeadline.value = false
  showDeadlineDatePickerFlag.value = false
}

// 点击外部关闭DatePicker和时间下拉框
// 会触发时间修改不正确 暂时停用
const handleClickOutside = (event: MouseEvent) => {
  // // 关闭任务时间DatePicker
  // if (showDatePickerFlag.value && timeRowRef.value && !timeRowRef.value.contains(event.target as Node)) {
  //   hideDatePicker()
  // }
  
  // // 关闭日期范围编辑
  // if (isEditingDateRange.value && timeRangeRowRef.value) {
  //   const f=timeRangeRowRef.value.contains(event.target as Node)
  //   if(!f){
  //     cancelDateRange()
  //   }
  // }
  
  // // 关闭终止时间DatePicker
  // if (showEndDatePickerFlag.value && timeRangeRowRef.value && !timeRangeRowRef.value.contains(event.target as Node)) {
  //   hideEndDatePicker()
  // }
  
  // // 关闭时间下拉框
  // if (showStartTimeDropdown.value && timeRangeRowRef.value && !timeRangeRowRef.value.contains(event.target as Node)) {
  //   showStartTimeDropdown.value = false
  // }
  
  // if (showEndTimeDropdown.value && timeRangeRowRef.value && !timeRangeRowRef.value.contains(event.target as Node)) {
  //   showEndTimeDropdown.value = false
  // }
}

// 监听点击事件
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  // 如果提供了初始时间，根据是否为全天进行初始化
  if (props.initialStartTime || props.initialEndTime) {
    isAllDay.value = props.initialAllDay ?? false
    if (!isAllDay.value) {
      activityEndDate.value = new Date(activityStartDate.value)
    } else if (activityEndDate.value <= activityStartDate.value) {
      activityEndDate.value = new Date(activityStartDate.value)
      activityEndDate.value.setDate(activityEndDate.value.getDate() + 1)
    }
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.base-card {
  position: fixed;
  width: 360px;
  min-height: 420px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e0e0e0;
  z-index: 1000;
  transition: transform 0.1s ease;
  user-select: none;
  display: flex;
  flex-direction: column;
}

.base-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  border-radius: 8px 8px 0 0;
  cursor: move;
  user-select: none;
}

.base-card-title {
  font-weight: 600;
  color: #333;
}

.base-card-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #666;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background 0.2s ease;
}

.base-card-close:hover {
  background: #e0e0e0;
  color: #333;
}

.base-card-content {
  padding: 16px;
  flex: 1;
}

/* 底部按钮样式 */
.base-card-footer {
  padding: 12px 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}

.save-button {
  background: #1976d2;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s ease;
}

.save-button:hover {
  background: #1565c0;
}

/* 标题输入框样式 */
.title-input-section {
  margin-bottom: 16px;
}

.title-input {
  width: 100%;
  border: none;
  border-bottom: 1px solid #e0e0e0;
  padding: 8px 0;
  font-size: 16px;
  font-weight: 600;
  outline: none;
  transition: border-color 0.2s ease;
}

.title-input:focus {
  border-bottom-color: #1976d2;
}

.title-input::placeholder {
  color: #999;
}

/* 标签按钮样式 */
.tab-buttons {
  display: flex;
  margin-bottom: 16px;
  border-bottom: 1px solid #e0e0e0;
}

.tab-button {
  flex: 1;
  padding: 8px 16px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.2s ease;
  position: relative;
}

.tab-button.active {
  color: #1976d2;
  font-weight: 600;
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background: #1976d2;
}

.tab-button:hover:not(.active) {
  background: #f5f5f5;
}

/* 活动内容样式 */
.activity-content,
.task-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.activity-row,
.task-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 0;
}

.time-range-row {
  position: relative;
}

/* 日期范围显示样式 */
.time-range-display {
  flex: 1;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  transition: all 0.2s ease;
  font-size: 14px;
  min-height: 44px;
  display: flex;
  align-items: center;
}

.display-content {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-range-text {
  flex: 1;
}

.edit-date-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1;
}

.edit-date-button:hover {
  background: #f5f5f5;
}

.edit-icon {
  font-size: 16px;
  pointer-events: none;
}

.edit-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 日期输入行样式 */
.date-inputs-row {
  display: flex;
  gap: 12px;
  width: 100%;
}

.date-input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.date-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.date-value {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  min-height: 36px;
  display: flex;
  align-items: center;
}

.fixed-date {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #e0e0e0;
}

.editable-date {
  border: 1px solid #e0e0e0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.editable-date:hover {
  background: #f8f9fa;
  border-color: #1976d2;
}

/* 全天行样式 */
.all-day-row {
  display: flex;
  align-items: center;
}

.all-day-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.all-day-checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.all-day-checkbox label {
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

/* 时间输入行样式 */
.time-inputs-row {
  display: flex;
  gap: 12px;
  width: 100%;
}

.time-input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.time-input-group label {
  font-size: 12px;
  color: #666;
}

.time-input-wrapper {
  position: relative;
}

.time-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s ease;
}

.time-input:focus {
  border-color: #1976d2;
}

.time-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.time-dropdown option {
  padding: 8px 12px;
  font-size: 14px;
}

.time-dropdown option:hover {
  background: #f5f5f5;
}

/* 日期范围操作按钮 */
.date-range-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  margin-top: 8px;
}

.confirm-btn,
.cancel-btn {
  padding: 6px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.confirm-btn {
  background: #1976d2;
  color: white;
  border-color: #1976d2;
}

.confirm-btn:hover {
  background: #1565c0;
}

.cancel-btn {
  background: white;
  color: #666;
}

.cancel-btn:hover {
  background: #f5f5f5;
}

/* 其他输入框样式 */
.location-input,
.note-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
  transition: border-color 0.2s ease;
}

.location-input:focus,
.note-input:focus {
  border-color: #1976d2;
}

.location-input::placeholder,
.note-input::placeholder {
  color: #999;
}

/* 任务相关样式 */
.time-row {
  position: relative;
}

.time-display,
.deadline-section {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  font-size: 14px;
}

.time-display:hover,
.deadline-section:hover {
  background: #f5f5f5;
}

/* 截止时间编辑样式 */
.deadline-display {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
}

.deadline-edit {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.deadline-date {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #1976d2;
  border-radius: 4px;
  background: #f0f8ff;
  cursor: pointer;
}

.deadline-cancel-btn {
  padding: 6px 12px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: white;
  color: #666;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.deadline-cancel-btn:hover {
  background: #f5f5f5;
}

/* DatePicker 容器样式 */
.date-picker-container {
  position: absolute;
  top: 100%;
  left: 0;
  z-index: 1002; /* 确保在 BaseCard 之上 */
  margin-top: 4px;
}

/* 任务时间 DatePicker 定位 */
.time-row {
  position: relative;
}

/* 截止时间 DatePicker 定位 */
.deadline-edit {
  position: relative;
}

/* 日期范围编辑中的 DatePicker 定位 */
.date-input-group {
  position: relative;
}

/* 调整 BaseCard 内容区域，确保有足够空间显示 DatePicker */
.base-card-content {
  position: relative;
  overflow: visible; /* 确保 DatePicker 可以显示在外部 */
}

/* 调整 BaseCard 的 z-index 确保 DatePicker 在其之上 */
.base-card {
  z-index: 1001;
}
</style>